package org.cancan.demo.init;

import lombok.extern.slf4j.Slf4j;
import org.cancan.demo.opencv.CameraCapture;
import org.cancan.demo.ws.WebSocketServer;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class StartVideoStartup implements CommandLineRunner {

    private CameraCapture cameraCapture = new CameraCapture();

    @Override
    public void run(String... args) throws Exception {
        while (true){
            Mat frame = cameraCapture.captureFrame();
            //将图像帧转为JPEG并发送
            byte[] imageData = encodeFrameToJPEG(frame);
            WebSocketServer.GroupBinarySending(imageData);
        }
    }

    private byte[] encodeFrameToJPEG(Mat frame){
        MatOfByte buffer = new MatOfByte();
        // 使用 Imgcodecs.imencode 方法将 Mat 类型的帧编码为 JPEG 格式，并存储在 buffer 中
        Imgcodecs.imencode(".jpg", frame, buffer);
        // 返回存储 JPEG 数据的字节数组
        return buffer.toArray();
    }

}
